import java
from java import io
import org.jfree
import jarray
from java.awt import Color,BasicStroke
from javax.swing import *
from Matrix import Matrix
from mfuncs import size;
import sets
import net.miginfocom.swing.MigLayout as MigLayout


def heatmap(console,x):
	if x is None:
		print "heatmap takes a matrix as input"
	pass


def saveObject(x,fname="jython.bin"):
	outs=io.ObjectOutputStream(io.FileOutputStream(fname))
	outs.writeObject(x)
	outs.close()
def loadObject(fname="jython.bin"):
	ins=io.ObjectInputStream(io.FileInputStream(fname))
	x=ins.readObject()
	ins.close()
	return x

class PyAction(java.awt.event.ActionListener):
	desktop = None;
	def __init__(self,list,console):
		self.list = list
		self.console = console 
		self.desktop = console.desktop

	def actionPerformed(self,e):
  
		if "add" == e.getActionCommand():
			   tfs=list(self.list.getSelectedValues());
			   Plabels=self.console.getVar('Plabels');
			   try:
			   	 tfa_ids=sets.Set(self.console.getVar('tfa_ids'))
			   except:
			   	 tfa_ids=sets.Set([])
			   for x in tfs:
			   	try:
					tfa_ids.add( Plabels.index(x))
				except:
					pass
			   self.console.putVar({'tfa_ids':list(tfa_ids)});
			   self.console.doInBackground('print "You have selected the following TFs: ", tfa_ids');
			   
		elif "finish" == e.getActionCommand():
			   self.console.doInBackground('[Af,Plabels]=Subnetwork(A0,Plabels,tfa_ids);Ef=Matrix(E0);')
		elif "plot" == e.getActionCommand():
			  tf=list(self.list.getSelectedValues());
			  Plabels=self.console.getVar('Plabels');
			  tf = tf[0]
			  idx = Plabels.index(tf)+1
			  plotstr = "plot(console," + idx.__repr__() + ",p,'" + tf + "',pdev,Plabels)"
			  print plotstr
			  self.console.doInBackground(plotstr)
		
def _select_TFs(console,Plabels):
	
	jl = JList(Plabels)
	jc = JScrollPane(jl)
	f = JInternalFrame('Select Regulators');
	l=MigLayout()
	f.setLayout(l)
	
	jb = JButton('Add')
	jb.setActionCommand("add")
	jf = JButton('Finish')
	jf.setActionCommand("finish")
	jf.addActionListener( PyAction(jl,console) )
	jb.addActionListener( PyAction(jl,console) )
	
	
	f.add(jc, "align left")
	f.add(jb,"align right")
	f.add(jf,"align right")
	
	f.pack();
	f.show()
	f.setClosable(True)
	console.desktop.add(f);
	
	
		
		
	# need to set call back for the button


# check if a real plot

def plot(console,idx,X,title=None,Xdev=None,xlabels=None,ylabels=None):
	
	[M,N]=size(X)
	if Xdev:
		series1 = org.jfree.data.xy.YIntervalSeries(xlabels[idx-1]);
		for n in xrange(1,N):
			y1 = X._M.get(idx-1,n-1)
			dev1 = Xdev._M.get(idx-1,n-1)
			series1.add(n, y1, y1 - dev1, y1 + dev1);

		x = org.jfree.data.xy.YIntervalSeriesCollection(); 
		x.addSeries(series1)
		render = org.jfree.chart.renderer.xy.DeviationRenderer()

	else:
		x = org.jfree.data.xy.XYSeries(xlabels[idx-1])
		for n in xrange(1,N):
			try:
				x.add(int(ylabels[n]),X[idx,n])
			except:
				x.add(n,X[idx,n]._M.get(0,0))
		x = org.jfree.data.xy.XYSeriesCollection(x)	
		
	chart = org.jfree.chart.ChartFactory.createXYLineChart(title,"Experiment","log Activity",x,org.jfree.chart.plot.PlotOrientation.VERTICAL,True,True,False)
	plot = chart.getPlot();
	plot.setBackgroundPaint(java.awt.Color.lightGray);
	plot.setAxisOffset(org.jfree.ui.RectangleInsets(5.0, 5.0, 5.0, 5.0));
	plot.setDomainGridlinePaint(java.awt.Color.white);
	plot.setRangeGridlinePaint(java.awt.Color.white);

	if Xdev != None:
		renderer = org.jfree.chart.renderer.xy.DeviationRenderer(True, False);
		renderer.setSeriesStroke(0, BasicStroke(3.0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
		renderer.setSeriesStroke(0, BasicStroke(3.0));
		renderer.setSeriesStroke(1, BasicStroke(3.0));
		renderer.setSeriesFillPaint(0, Color(200, 200, 255));
		renderer.setSeriesFillPaint(1, Color(255, 200, 200));
		plot.setRenderer(renderer);

		yAxis = plot.getRangeAxis();
		yAxis.setAutoRangeIncludesZero(True);
		#yAxis.setStandardTickUnits(org.jfree.chart.axis.NumberAxis.createIntegerTickUnits()); 

	mChart = org.jfree.chart.ChartPanel(chart)
	frame = JInternalFrame(title);
	frame.setSize(400, 400);
	frame.setContentPane(mChart);
	frame.setVisible(True);
	frame.setClosable(True);
	frame.setResizable(True);
	frame.setIconifiable(True);
	console.desktop.add(frame)
	frame.setSelected(True)
